package com.niocholas.study.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @author ze.dong
 * @version 创建时间：2020/5/12
 */
@Slf4j
public class StudyThread {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        Thread t1 = new Thread(() -> {
            log.info("hello , I am t1");
        }, "study-java-thread-t1");
        Thread t2 = new Thread(() -> {
            log.info("hello , I am t2");
        }, "study-java-thread-t2");
        t1.start();
        t2.start();
        Thread.sleep(500L);


        // 使用
        ExecutorService executor = Executors.newCachedThreadPool();
        Task task = new Task();
        Future<Integer> result = executor.submit(task);
        // 注意调用get方法会阻塞当前线程，直到得到结果。
        // 所以实际编码中建议使用可以设置超时时间的重载get方法。
        System.out.println(result.get());

        FutureTask<Integer> futureTask = new FutureTask<>(new Task());
        executor.submit(futureTask);
        System.out.println(futureTask.get());


        Thread testThread = new Thread(() -> {
            System.out.println("testThread当前线程组名字：" +
                    Thread.currentThread().getThreadGroup().getName());
            System.out.println("testThread线程名字：" +
                    Thread.currentThread().getName());
        });
        testThread.start();

        System.out.println("执行main方法线程名字：" + Thread.currentThread().getName());

    }


}

// 自定义Callable
class Task implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        // 模拟计算需要一秒
        Thread.sleep(1000);
        return 2;
    }
}
